using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows;
using System.ComponentModel;
using System.Windows.Media;
using KarliCardsGui.ViewModels;
using System.Collections.Generic;

namespace KarliCardsGui.Converters
{
    public class RandomCardBackConverter : IValueConverter
    {
        private static readonly Random random = new Random();
        private static int currentBackgroundIndex = 0;
        private static readonly string[] cardBacks = new[]
        {
            "pack://application:,,,/Images/card_back_01.png",
            "pack://application:,,,/Images/card_back_02.png",
            "pack://application:,,,/Images/card_back_03.png"
        };

        private static BitmapImage currentBackground;
        
        // 添加刷新委托
        public static Action<List<CardViewModel>> RefreshCards { get; set; }

        static RandomCardBackConverter()
        {
            currentBackground = new BitmapImage(new Uri(cardBacks[0]));
        }

        public static void ChangeBackground()
        {
            // 按顺序循环切换背景索引
            currentBackgroundIndex = (currentBackgroundIndex + 1) % cardBacks.Length;
            
            // 强制创建新的图片实例并加载
            var newBackground = new BitmapImage();
            newBackground.BeginInit();
            newBackground.UriSource = new Uri(cardBacks[currentBackgroundIndex]);
            newBackground.CacheOption = BitmapCacheOption.OnLoad;
            newBackground.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            newBackground.EndInit();
            newBackground.Freeze(); // 提高性能
            
            // 更新当前背景
            currentBackground = newBackground;
            
            // 输出当前背景索引，用于调试
            Console.WriteLine($"Changed background to index: {currentBackgroundIndex}");
            
            // 通知所有卡牌更新背景
            Application.Current.Dispatcher.Invoke(() =>
            {
                RefreshCards?.Invoke(null);
            });
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isFaceUp = (bool)value;
            if (!isFaceUp)
            {
                return currentBackground;
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
} 